package cn.sf.sufinguserprovider.serviceImpl;

import cn.sf.pojo.User;
import cn.sf.service.UserService;
import cn.sf.sufinguserprovider.dao.AttentionMapper;
import cn.sf.sufinguserprovider.dao.UserMapper;
import cn.sf.util.RedisUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private AttentionMapper attentionMapper;

    @Resource
    private RedisUtil redisUtil;


    /**
     * 用来测试，给Redis中添加值的方法
     *
     * @param id
     * @return
     */
    @Override
    @RequestMapping("/queryInformation")
    public String queryInformation(Long id) {
        User user = userMapper.queryInformation(id);
        redisUtil.set("user:" + id, JSON.toJSONString(user));
        String s = redisUtil.get("user:" + id);
        return s;
    }

    /**
     * 修改用户信息先去删除Redis中用户信息，再修改MySQL中的用户信息，然后再添加到Redis中信息
     *
     * @param user
     * @return
     */
    @Override
    @RequestMapping("/updateUserById")
    public String updateUserById(@RequestBody User user) {
        boolean del = redisUtil.del("user:" + user.getUserId());
        if (del) {
            int count = userMapper.updateUserById(user);
            if (count > 0) {
                User user1 = userMapper.queryInformation(user.getUserId());
                redisUtil.set("user:" + user.getUserId(), JSON.toJSONString(user1));
                return "true";
            }
        }
        return "false";
    }


    /**
     * 根据用户id去Redis中查询用户信息
     *
     * @param id
     * @return
     */
    @Override
    @RequestMapping("/getRedisUserById")
    public User getRedisUserById(Long id) {
        String user = redisUtil.get("user:" + id);
        System.out.println(user);
        User parse = JSON.parseObject(user, User.class);
        return parse;
    }



    @RequestMapping("/queryUser")
    public User queryUser(String userCode, String userPassword) {
/*        if (userCode==null || userPassword==null ){
            return null;
        }*/
        System.out.println("userCode:" + userCode);
        return userMapper.queryUser(userCode, userPassword);
    }


    @RequestMapping("/userAdd")
    public int userAdd(@RequestBody User user) {
        System.out.println("name:" + user.getUserCode());
        return userMapper.userAdd(user);
    }

    @Override
    @RequestMapping("/queryIsOrNotAttention")
    public boolean queryIsOrNotAttention(long userId1, long userId2) {
        if (attentionMapper.queryIsOrNotAttention(userId1, userId2) > 0) {
            return true;
        }
        return false;
    }

    /**
     * 关注用户信息
     * 取消关注该用户
     *
     * @param userId1 登录用户ID
     * @param userId2 视频用户ID
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("/userAttention")
    public String userAttention(long userId1, long userId2) throws Exception {
        try {
            //查询是否关注过这个用户
            User loginUser = userMapper.selUserAttentionInfo(userId1);   //查询登录用户信息
            if (attentionMapper.queryIsOrNotAttention(userId1, userId2) == 0) {
                //若没有该用户则向用户表中修改用户关注量和粉丝量
                loginUser.setUserAttention(loginUser.getUserAttention() + 1);
                User videoUser = userMapper.selUserAttentionInfo(userId2);   //查询视频用户信息
                videoUser.setUserFans(videoUser.getUserFans() + 1);
                if (userMapper.updUserNumber(loginUser) > 0 && userMapper.updUserNumber(videoUser) > 0) {
                    //向关注表中插入数据
                    if (attentionMapper.addUserAttention(userId1, userId2) > 0) {
                        return "关注成功";
                    }
                    throw new RuntimeException("执行添加关注失败");
                }
                throw new RuntimeException("执行修改用户关注数和粉丝数出错");
            } else {
                //若关注该用户则向用户表中修改用户关注量和粉丝量-1
                loginUser.setUserAttention(loginUser.getUserAttention() - 1);
                User videoUser = userMapper.selUserAttentionInfo(userId2);   //查询视频用户信息
                videoUser.setUserFans(videoUser.getUserFans() - 1);
                if (userMapper.updUserNumber(loginUser) > 0 && userMapper.updUserNumber(videoUser) > 0) {
                    //删除关注表中的该数据
                    if (attentionMapper.delUserAttention(userId1, userId2) > 0) {
                        return "取消关注成功";
                    }
                    throw new RuntimeException("执行取消关注失败");
                }
                throw new RuntimeException("执行修改用户关注数和粉丝数-1出错");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//抛了异常后是会回滚的
            return "执行关注操作失败";
        }
    }


    /**
     * 修改用户头像
     *
     * @param userHead
     * @param userId
     * @return 200返回成功，402数据库设置失败
     */
    @Override
    @RequestMapping("/uploadHead")
    public String uploadHead(String userHead, Long userId) {
        int num = userMapper.updateUserHeadUrl(userHead, userId);
        if (num > 0) {
            User user1 = userMapper.queryInformation(userId);
            redisUtil.set("user:" + userId, JSON.toJSONString(user1));
            System.out.println("修改成功");
            return "200";
        }
        System.out.println("修改失败");
        return "402";
    }



    /**
     * 查询用户的动态
     * @param userId 用户ID
     * @return
     */
    @Override
    @RequestMapping("/queryUserDynamicById")
    public List<User> queryUserDynamicById(long userId) {
        return userMapper.queryUserDynamicById(userId);
    }

    /**
     * 根据用户Id查询关注者的动态列表
     * @param userId
     * @return
     */
    @Override
    @RequestMapping("/queryUserAllDynamicById")
    public List<User> queryUserAllDynamicById(long userId) {
        return userMapper.queryUserAllDynamicById(userId);
    }

    /**
     * 查询用户小面板
     * @param userId 用户ID
     * @return
     */
    @Override
    @RequestMapping("/queryUserPanelById")
    public User queryUserPanelById(long userId) {
        return userMapper.queryUserPanelById(userId);
    }
}
